package com.hcc.gateway.netty.support;

import cn.hutool.core.io.FileUtil;
import com.hcc.gateway.netty.context.RespContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * WriteRespUtils
 *
 * @author shengjun.hu
 * @date 2021/12/28
 */
public class WriteRespUtils {

    private WriteRespUtils() {}

    public static void writeRespFor404(RespContext respContext) {
        String content = FileUtil.readString("template/404.ftl", StandardCharsets.UTF_8);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("msg", "Not Found");
        String result = TemplateUtils.convertFreeMakerTemplate("template404", content, paramMap);

        respContext.setHttpStatus(HttpResponseStatus.NOT_FOUND);
        respContext.getHeaders().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
        respContext.setBody(ByteBufUtils.writeStringToByteBuf(result));
    }

    public static void writeRespFor500(RespContext respContext, Throwable t) {
        String content = FileUtil.readString("template/500.ftl", StandardCharsets.UTF_8);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("msg", t.getMessage());
        paramMap.put("stackTrace", t.getStackTrace());
        String result = TemplateUtils.convertFreeMakerTemplate("template500", content, paramMap);

        respContext.setHttpStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        respContext.getHeaders().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
        respContext.setBody(ByteBufUtils.writeStringToByteBuf(result));
    }

    public static void writeRespForHello(RespContext respContext, Throwable t) {
        String content = FileUtil.readString("template/hello.ftl", StandardCharsets.UTF_8);
        Map<String, Object> paramMap = new HashMap<>();
        String result = TemplateUtils.convertFreeMakerTemplate("hello", content, paramMap);

        respContext.setHttpStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        respContext.getHeaders().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
        respContext.setBody(ByteBufUtils.writeStringToByteBuf(result));
    }

}
